let exec = require("child_process").exec;
const Ci = require(`./ci.js`);
let http = require("http");
let fs = require("fs");
let path = require("path");
const TOOLS = require(`./tools.js`);

let finishedDeploy = [];
let deployList = null;

let start = (deployList) => {
  let taskTime = Math.fround(new Date());
  let fn = (deploy, current, e) => {
    let Info = e.toString();
    let date = new Date();
    if (Info.indexOf("done: upload") === 0) {
      finishedDeploy.push({
        speed: `[${current + 1}/${deployList.length}]`,
        app: deploy.name,
        status: "finished",
        time: date,
      });
      TOOLS.Log.writeLog(
        taskTime,
        JSON.stringify({
          speed: `[${current + 1}/${deployList.length}]`,
          app: ` ${deploy.name}`,
          status: `finished`,
          time: ` ${date}`,
        })
      );
      if (current < deployList.length - 1) {
        Ci.deploy(deployList, ++current, fn);
      }
    }
  };
  Ci.deploy(deployList, 0, fn);
};

let router = async (req, res) => {
  let route = req.url;
  let method = req.method;
  if (route === "/dashboard" && method === "GET") {
    res.setHeader("Content-Type", "text/html");
    fs.readFile(path.join(__dirname, `./index.html`), (err, data) => {
      if (err) {
        console.log(err, "err");
      } else {
        res.end(data);
      }
    });
  }

  if (route === "/postdata" && method === "POST") {
    console.log("pooooooot")
    res.setHeader("Content-Type", "application/json");
    deployList = await ((require) => {
      return new Promise((resolve, reject) => {
        let postData = "";
        require.on("data", (chunk) => {
          postData += chunk;
        });
        require.on("end", () => {
          postData = JSON.parse(postData);
          resolve(postData);
        });
      });
    })(req);
    deployList = TOOLS.recombination(deployList);
    let packageMsg = TOOLS.getPackageSize(deployList[0].project);
    let isPass = TOOLS.checkPackageSize(packageMsg.countSize, packageMsg.subPackages);
    if (!isPass.isPass) {
      res.end(JSON.stringify({ status: "error", message: isPass }));
      return;
    }
    start(deployList);
    res.end(JSON.stringify({ status: "success", message: "提交成功" }));
  }

  if (route === "/result" && method === "GET") {
    res.setHeader("Content-Type", "application/json");
    if (deployList === null || deployList === undefined || deployList === "") {
      res.end(JSON.stringify({ status: "error", message: "请先提交发布数据" }));
    } else {
      if (finishedDeploy.length < deployList.length) {
        res.end(JSON.stringify({ status: "success", type: "ing", data: finishedDeploy }));
      } else {
        res.end(JSON.stringify({ status: "success", type: "end", data: finishedDeploy }));
      }
    }
  }
};
module.exports = gui = (port) => {
  let httpServer = async (port) => {
    let server = http.createServer();
    server.on("request", async (req, res) => {
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
      router(req, res);
    });

    server.listen(port, () => {
      console.log("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
      console.log(`Please open this address in the browser: 127.0.0.1:${port}`);
      console.log("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
    });
  };
  httpServer(port);
  exec(`start http://127.0.0.1:${port}/dashboard`);
};
